package com.gitee.wsl.net.client.login

import com.gitee.wsl.net.server.role.admin.AdminResponse
import com.gitee.wsl.time.format.convertCookieTimeToISO8601
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.delete
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import kotlinx.datetime.Instant
import kotlinx.serialization.Serializable


/**
 * Auth request
 *
 * @property email
 * @property password
 */
@Serializable
data class LoginRequest(
    val email: String,
    val password: String,
)

/**
 * Session cookie response
 */
@Serializable
data class SessionCookieResponse(
    val name: String,
    val value: String,
    val path: String,
    val maxAge: Int,
    val expires: Long,
)

/**
 * Login method
 */
@Throws(Exception::class)
suspend fun HttpClient.login(request: LoginRequest): AdminResponse {
    return post("api/login") { setBody(request) }.body()
}

/**
 * Login method
 */
@Throws(Exception::class)
suspend fun HttpClient.loginCookie(request: LoginRequest): SessionCookieResponse {
    post("api/login") { setBody(request) }.headers["Set-Cookie"]?.let {

        var name = ""
        var value = ""
        var path = ""
        var maxAge = 0
        var expires = 0L

        it.split(";").forEachIndexed { index, item ->
            if (index == 0) {
                name = item.split("=")[0].trim()
                value = item.split("=")[1].trim()
            } else if (item.contains("Path")) {
                path = item.split("=")[1].trim()
            } else if (item.contains("Max-Age")) {
                maxAge = item.split("=")[1].trim().toInt()
            } else if (item.contains("Expires")) {
                expires = Instant.parse(
                    convertCookieTimeToISO8601(item.split("=")[1].trim())
                ).toEpochMilliseconds()
            }
        }

        return SessionCookieResponse(
            name = name,
            value = value,
            path = path,
            maxAge = maxAge,
            expires = expires,
        )
    }

    throw RuntimeException("Error get cookie session")
}

/**
 * Delete session
 */
@Throws(Exception::class)
suspend fun HttpClient.logout() {
    delete("api/logout")
}